﻿namespace DeviceController.Wpf.Utils
{
    /// <summary>
    /// LED 灯管的三种状态
    /// </summary>
    public enum LedStatus
    {
        /// <summary>
        /// 打开灯管
        /// </summary>
        Open,

        /// <summary>
        /// 关闭灯管
        /// </summary>
        Close,

        /// <summary>
        /// 保留灯管状态，无论打开或关闭与否
        /// </summary>
        Reserved
    }

    /// <summary>
    /// LED 灯管控制器
    /// </summary>
    internal class LedController
    {
        private readonly PIDController _pid;

        private readonly double _maxValue;

        private readonly double _minValue;

        private readonly double _targetValue;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="maxValue">极片最大厚度</param>
        /// <param name="minValue">极片最小厚度</param>
        public LedController(double maxValue, double minValue)
        {
            _maxValue = maxValue;
            _minValue = minValue;
            _targetValue = (minValue + maxValue) / 2;
            // 比例系数，稳态误差系数，变化率系数。
            _pid = new PIDController(0.01, 0.2, 0.01);
        }

        /// <summary>
        /// 计算 LED 灯管状态
        /// </summary>
        /// <param name="currentThickness">输入当前厚度数据</param>
        /// <returns>返回 LED 灯管需要设置的状态</returns>
        public LedStatus CalculateLedStatus(double currentThickness)
        {
            var err = _pid.Calculate(_targetValue, currentThickness);
            var nextValue = currentThickness + err;

            if (nextValue > _maxValue)
            {
                return LedStatus.Close;
            }
            else
            if (nextValue < _minValue)
            {
                return LedStatus.Open;
            }

            return LedStatus.Reserved;
        }
    }
}
